package com.prb.dao.impl;

import com.prb.annotation.Autowrite;
import com.prb.annotation.Compoant;
import com.prb.dao.AccountDao;
import com.prb.entity.Account;
import com.prb.factory.ConnectionFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Compoant
public class AccountDaoImpl implements AccountDao {

    @Autowrite
    private ConnectionFactory connectionFactory;

    @Override
    public Account queryAccount(String cardNo) throws SQLException {

        Connection connection = connectionFactory.openConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from account where cardNo = ?");
        preparedStatement.setString(1 , cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while (resultSet.next()){
            account.setCardNo(cardNo);
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }

        resultSet.close();
        preparedStatement.close();

        return account;
    }

    @Override
    public boolean doTrans(String cardNo , Integer money) throws SQLException {

        Connection connection = connectionFactory.openConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("update account set money = ? where cardNo = ?");
        preparedStatement.setInt(1 , money);
        preparedStatement.setString(2 , cardNo);

        boolean result = preparedStatement.execute();

        preparedStatement.close();

        return result;

    }
}
